import { resourceLibraryApi } from '@/api';
import { YmResponseCode } from '@/api/request/core';
import { EnCourseWareGroup } from '@/common';
import CusModal from '@/components/CusModal';
import IconFont from '@/components/IconFont';
import AddOrEditFolderForm from '@/components/resourceLibraryComp/AddOrEditFolderForm';
import type { IFolderFormProps, TFolderRef } from '@/components/resourceLibraryComp/AddOrEditFolderForm/interface';
import FilePaths from '@/components/resourceLibraryComp/FilePaths';
import type { RefFn } from '@/components/resourceLibraryComp/FilePaths/interface';
import ResourceNameForTable from '@/components/resourceLibraryComp/ResourceNameForTable';
// import { unifyConfirm } from '@/utils/compUtils';
import CusDrawer from '@/components/CusDrawer';
import type { SearchValue, TableRecord } from '@/components/resourceLibraryComp/common/interface';
import TestPaperDetail from '@/components/resourceLibraryComp/TestPaperDetail';
import { App, Button, message, Space } from 'antd';
import React, { useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import type { YmTablePorps } from 'ym-design';
import { YmTable } from 'ym-design';

const DRAWERWIDTH = 680;
function TestPaper() {
  const courseWareFlag = 'testPaper';
  const {
    modal: { confirm },
  } = App.useApp();
  const navigator = useNavigate();
  const filePathsRef = useRef<RefFn>(null);
  const addOrEditFolderRef = useRef<TFolderRef>(null);
  const [currRowParentId, setCurrRowParentId] = useState<string>('0');
  const [currRowResourceId, setCurrRowResourceId] = useState<string>();
  const [refreshFlag, _setRefreshFlag] = useState(false);
  const [modalBtnStatus, setModalBtnStatus] = useState({ loading: false, disabled: false }); //modal框按钮状态
  const [isModalShow, setIsModalShow] = useState<{ show: boolean; type?: string }>({ show: false });
  const [configModal, setConfigModal] = useState<{ title: string; children: React.ReactNode }>();
  const [drawerOpen, setDrawerOpen] = useState(false);

  // 刷新table的 flag
  function refreshTable() {
    _setRefreshFlag((v) => !v);
  }

  // 点击行
  const handleRowClick = (event: React.MouseEvent, record: TableRecord) => {
    const { resourceId, resourceType, resourceName } = record;
    if (resourceType !== 1) return;
    setCurrRowParentId(resourceId);
    filePathsRef.current?.onAddFilePaths({ resourceId, resourceName });
  };

  // 打开创建/编辑文件夹Modal
  const onOpenAddOrEditFolderModal = (param: IFolderFormProps) => {
    const { type } = param;
    setIsModalShow({ show: true, type });
    setConfigModal({
      title: type === 'add' ? '新增文件夹' : '重命名文件夹',
      children: <AddOrEditFolderForm ref={addOrEditFolderRef} {...param} />,
    });
  };

  //新建/重命名 文件夹 接口
  const addOrEditResourceCatagoryCatalogApi = (values: IFolderFormProps) => {
    const { resourceName, type, resourceId } = values;
    const param = { coursewareGroup: EnCourseWareGroup[courseWareFlag], resourceName };
    const requestApi =
      type === 'add'
        ? resourceLibraryApi.createResourceCatalog({ parentId: currRowParentId, ...param })
        : resourceLibraryApi.editResourceCatalog({ resourceId, ...param });
    requestApi.then((res) => {
      refreshTable();
    });
  };

  // 关闭modal
  const closeModal = () => {
    setIsModalShow({ show: false });
  };

  //点击modal保存按钮
  const confirmModal = () => {
    setModalBtnStatus({ disabled: true, loading: true });
    // if (isModalShow.type === 'add') {
    addOrEditFolderRef.current
      ?.onSubmit()
      .then((values) => {
        addOrEditResourceCatagoryCatalogApi(values);
      })
      .finally(() => {
        setModalBtnStatus({ disabled: false, loading: false });
        closeModal();
      });
    // }
  };

  // modal框配置
  const modalConst = {
    open: isModalShow.show,
    width: 420,
    centered: true,
    destroyOnClose: true,
    footer: [
      <Button key="back" disabled={modalBtnStatus.disabled} onClick={closeModal}>
        取消
      </Button>,
      <Button type="primary" key="save" loading={modalBtnStatus.loading} onClick={confirmModal}>
        保存
      </Button>,
    ],
    onCancel: closeModal,
  };

  // 删除文件夹/资源
  const onResourceDelete = (record: TableRecord) => {
    const { resourceType, resourceName, resourceId } = record;
    // deleteResourceCatalog ,deleteCourseWare
    const confirmContent =
      resourceType === 1 ? (
        <div>
          <p> 确定要删除【{resourceName}】文件夹吗？</p>
          <p>删除后文件夹中的内容也会同步删除！</p>
        </div>
      ) : (
        `确定要删除 【${resourceName}】吗？`
      );

    confirm({
      content: confirmContent,
      centered: true,
      onOk: () => {
        const requestApi =
          resourceType === 1
            ? resourceLibraryApi.deleteResourceCatalog({ resourceId })
            : resourceLibraryApi.deleteCourseWare({ coursewareId: resourceId });
        requestApi.then((res) => {
          const { code, msg } = res;
          code === YmResponseCode.normal ? message.success(msg) : message.error(msg);
          refreshTable();
        });
      },
    });
  };

  function _getAddPageName(courseWareFlagParam: string) {
    const courseWarePageName =
      'add' + courseWareFlagParam.substring(0, 1).toLocaleUpperCase() + courseWareFlagParam.substring(1);
    return courseWarePageName;
  }

  // 点击 column 重命名/编辑按钮
  const handleEdit = (e: React.MouseEvent, record: TableRecord) => {
    e.stopPropagation();

    const { resourceId, resourceName } = record;
    if (record.resourceType === 1) {
      // 文件夹
      onOpenAddOrEditFolderModal({ type: 'edit', resourceId, resourceName });
    } else {
      navigator(
        `/resourceLibrary/${_getAddPageName(
          courseWareFlag,
        )}?type=edit&parentId=${currRowParentId}&resourceId=${resourceId}`,
      );
    }
  };

  //试卷详情drawer 配置
  const drawerConfig = useMemo(() => {
    return {
      title: '试卷详情',
      width: DRAWERWIDTH,
      open: drawerOpen,
      onClose: () => {
        setDrawerOpen(false);
      },
      destroyOnClose: true,
      children: <TestPaperDetail coursewareId={currRowResourceId!} />,
    };
  }, [currRowResourceId, drawerOpen]);

  const columns: YmTablePorps<TableRecord, SearchValue>['columns'] = useMemo(
    () => [
      {
        dataIndex: 'resourceName',
        title: '文件夹名称',
        key: 'resourceName',
        fixed: 'left',
        width: 400,
        ellipsis: true,
        render: (text, record) => (
          <ResourceNameForTable title={text} resourceType={record.resourceType} resourceFrom={courseWareFlag} />
        ),
      },
      {
        dataIndex: 'modifyTime',
        title: '修改时间',
        key: 'modifyTime',
        width: 220,
      },
      {
        dataIndex: 'coursewareNum',
        title: '课件数量',
        key: 'coursewareNum',
        width: 120,
        render: (text, record) => <span>{record.resourceType == 1 ? text : 1}</span>,
      },
      {
        title: '操作',
        key: 'action',
        width: 150,
        fixed: 'right',
        render: (text, record) => {
          return (
            <Space direction="horizontal" size={0}>
              {record.resourceType !== 1 && (
                <Button
                  type="text"
                  size="small"
                  onClick={(e: React.MouseEvent) => {
                    e.stopPropagation();
                    setCurrRowResourceId(record.resourceId);
                    setDrawerOpen(true);
                  }}
                >
                  <span className="safe-edu_table_operation_text">详情</span>
                </Button>
              )}
              <Button
                type="text"
                size="small"
                onClick={(e: React.MouseEvent) => {
                  handleEdit(e, record);
                }}
              >
                <span className="safe-edu_table_operation_text">{record.resourceType === 1 ? '重命名' : '编辑'}</span>
              </Button>
              <Button
                type="text"
                size="small"
                onClick={(e: React.MouseEvent) => {
                  e.stopPropagation();
                  onResourceDelete(record);
                }}
              >
                <span className="safe-edu_table_operation_text">删除</span>
              </Button>
            </Space>
          );
        },
      },
    ],
    [refreshFlag, currRowParentId],
  );

  return (
    <div className="safe_boss_page">
      <YmTable<TableRecord, SearchValue>
        columns={columns}
        rowKey="resourceId"
        searchForm={{
          formItems: [
            {
              name: 'resourceName',
              label: '名称',
              valueType: {
                type: 'input',
                inputProps: {
                  placeholder: '请输入',
                },
              },
            },
          ],
        }}
        toolBar={{
          prefixNode: (
            <div className="safe-edu_table_toolbar_prefix_box">
              <Button
                type="primary"
                onClick={() => {
                  navigator(`/resourceLibrary/${_getAddPageName(courseWareFlag)}?type=add&parentId=${currRowParentId}`);
                }}
              >
                新增
              </Button>
              <Button
                onClick={() => {
                  onOpenAddOrEditFolderModal({ type: 'add' });
                }}
                icon={<IconFont type="icon-xinjianwenjianjia" />}
              >
                新建文件夹
              </Button>
            </div>
          ),
        }}
        request={async ({ page = {} }, searchValue) => {
          const { pageIndex: pageNum, pageSize } = page;
          const { resourceName } = searchValue!;
          // console.log('--page--:', page);
          // console.log('---searchValue--:', searchValue);
          const courseWareData = await resourceLibraryApi.searchResourceCatalogList({
            coursewareGroup: EnCourseWareGroup[courseWareFlag],
            parentId: currRowParentId,
            pageSize,
            pageNum,
            resourceName,
          });

          return courseWareData.data;
        }}
        requestOptions={{
          reFreshDep: [currRowParentId, refreshFlag, courseWareFlag],
        }}
        onRow={(record) => {
          return {
            onClick: (e) => {
              handleRowClick(e, record);
            },
          };
        }}
      >
        {({ formNode, tableNode, tabsNode, toolBarNode }) => {
          return (
            <>
              {formNode}
              {tabsNode}
              {toolBarNode}
              <FilePaths
                ref={filePathsRef}
                onBreadCrumbClick={(e, key) => {
                  setCurrRowParentId(key);
                }}
              />
              {tableNode}
            </>
          );
        }}
      </YmTable>

      <CusModal {...modalConst} {...configModal} />
      <CusDrawer {...drawerConfig} />
    </div>
  );
}

export default TestPaper;
